package com.heima.user.filter;


import com.heima.model.user.pojo.ApUser;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Component
@WebFilter(filterName = "appTokenFilter",urlPatterns = "/*") //全路径覆盖
@Order(1)
public class AppTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将请求转换为http请求
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //获得请求头中是否由用户id
        String userId = httpServletRequest.getHeader("userId");
        //如果用户id存在
        if (StringUtils.isNotEmpty(userId)&& Integer.valueOf(userId) != 0) {
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            //将该用户设置到当前线程
            AppThreadLocalUtils.setUser(apUser);
        }
        //方行
        filterChain.doFilter(servletRequest,servletResponse);
        //清空登录信息
        AppThreadLocalUtils.clear();
    }
}
